package com.rcadmin.busi.admin.service;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import com.rcadmin.busi.admin.dao.SysMenuDao;
import com.rcadmin.busi.admin.ddl.SysMenu;
import com.rcadmin.common.bean.MenuObject;
import com.rcadmin.core.jpa.DaoException;

/**
 * 系统菜单服务类
 * 
 * @author tanson lam
 * @create 2016年9月6日
 */
@Component
@CacheConfig(cacheNames = "sysMenu")
public class SysMenuService {
	@Resource
	private SysMenuDao sysMenuDao;

	/**
	 * 查询菜单，构建菜单树结构
	 * 
	 * @param userInfo
	 * @throws DaoException
	 */ 
    @Cacheable 
	public List<MenuObject> queryModuleTree() throws DaoException {
		List<SysMenu> menuList = sysMenuDao.getAllMenu();
		List<MenuObject> moduleList = new ArrayList<MenuObject>();
		for (int i = 0; i < menuList.size(); i++) {
			SysMenu sysMenu = (SysMenu) menuList.get(i);
			MenuObject treeObject = copy2TreeObject(sysMenu);
			moduleList.add(treeObject);
		}
		for (MenuObject t1 : moduleList) {
			for (MenuObject t2 : moduleList) {
				if (t2.getParentId().equals(t1.getId())) {
					List<MenuObject> childList = t1.getChildren();
					if (childList == null) {
						childList = new ArrayList<MenuObject>();
						t1.setChildren(childList);
					}
					childList.add(t2);
				}
			}
		}
		return moduleList;
	}

	private MenuObject copy2TreeObject(SysMenu sysMenu) {
		MenuObject treeObject = new MenuObject();
		treeObject.setId(sysMenu.getId());
		treeObject.setText(sysMenu.getName());
		String url = null;
		Integer parentId = sysMenu.getParentid() == 0 ? sysMenu.getId()
				: sysMenu.getParentid();
		if (sysMenu.getUrl() != null) {
			if (sysMenu.getUrl().indexOf("?") != -1)
				url = sysMenu.getUrl() + "&parentMenuId=" + parentId
						+ "&menuId=" + sysMenu.getId();
			else
				url = sysMenu.getUrl() + "?parentMenuId=" + parentId
						+ "&menuId=" + sysMenu.getId();
		}
		treeObject.setHrefTarget(url);
		treeObject.setIconCls(sysMenu.getIcon());
		treeObject.setLevel(sysMenu.getLevel());
		treeObject.setParentId(sysMenu.getParentid());
		return treeObject;
	}
}
